import {expect} from 'chai';
import * as sinon from 'sinon';
import * as os from 'os';
import * as path from 'path';
import {generateLineAndNetrc} from '../src/setup';

const mockStep = {
    info: sinon.stub(),
    certificate: {
        getCodeupCertificate: sinon.stub()
    },
    platform: {
        getPlatform: sinon.stub().returns('linux'),
        PLATFORM_WIN: 'win'
    }
};

const mockProcess = {
    env: {
        FLOW_JOB_TOKEN: 'mocked-flow-job-token',
        SERVICE_CONNECTION_ID: 'mocked-service-connection-id'
    }
};
const mockFs = {
    writeFileSync: sinon.stub()
};

const proxyquire = require('proxyquire');
const setup = proxyquire('../src/setup', {
    '@ali/flow-step-toolkit': mockStep,
    'process': mockProcess,
    'fs': mockFs
});

describe('setup function', () => {
    beforeEach(() => {
        sinon.reset();
    });

    it('should call getCodeupCertificate with correct parameters and write the correct data to the .netrc file', async () => {
        const expectedCodeupCertificate = {
            host: 'mocked-host',
            username: 'mocked-user',
            password: 'mocked-password'
        };
        mockStep.certificate.getCodeupCertificate.resolves(expectedCodeupCertificate);

        await setup.setup();
        const netrcPath = path.resolve(os.homedir(), '.netrc');
        const expectedData = `machine mocked-host login mocked-user password mocked-password\n`;

        sinon.assert.calledWith(mockStep.certificate.getCodeupCertificate, 'mocked-flow-job-token', 'mocked-service-connection-id')
        sinon.assert.calledWith(mockFs.writeFileSync, netrcPath, expectedData, {flag: 'a', mode: 0o600})
    });
});

describe('generateLineAndNetrc', () => {
    const machine = 'example.com';
    const username = 'user';
    const password = 'pass';

    it('should generate line and netrc for linux/darwin platform', () => {
        const platform = 'linux';
        const {line, netrc} = generateLineAndNetrc(machine, username, password, platform);

        expect(line).to.equal(`machine ${machine} login ${username} password ${password}\n`);
        expect(netrc).to.equal(path.resolve(os.homedir(), ".netrc"));
    });

    it('should generate line and netrc for windows platform', () => {
        const platform = 'win';
        const {line, netrc} = generateLineAndNetrc(machine, username, password, platform);

        expect(line).to.equal(`machine ${machine}\nlogin ${username}\npassword ${password}\n`);
        expect(netrc).to.equal(path.resolve(os.homedir(), "_netrc"));
    });
});
